﻿using System;
using Evpo.ContactData.ViewModel;
using System.Collections.Specialized;
using Evpo.ContactData.Common;
using System.Web;

namespace Evpo.ContactData.UI.GeneralClasses
{
    public abstract class ListUrlComposer
    {
        public ListUrlComposer(Uri baseUrl)
        {
            _baseUrl = baseUrl;
        }


        #region Fields
        protected readonly Uri _baseUrl;
        #endregion

        #region Properties
        
        public Uri NextPageUrl
        {
            get
            {
                Uri next = UrlHelper.SetQueryParam(
                        CurrentUrl, "PageBegin", ListViewModel.NextPageBegin.ToString());
                next = UrlHelper.SetQueryParam(
                    next, "PageEnd", ListViewModel.NextPageEnd.ToString());
                return next;
            }
        }

        public Uri PrevPageUrl
        {
            get
            {
                Uri prev = UrlHelper.SetQueryParam(
                        CurrentUrl, "PageBegin", ListViewModel.PrevPageBegin.ToString());
                prev = UrlHelper.SetQueryParam(
                    prev, "PageEnd", ListViewModel.PrevPageEnd.ToString());
                return prev;
            }
        }

        internal Uri CurrentUrl
        {
            get
            {
                UriBuilder builder = new UriBuilder(_baseUrl);

                builder.Query = CreateQueryCollection(builder.Query, ListViewModel.ListQuery).ToString();
                return builder.Uri;
            }
        }


        protected abstract ListViewModel ListViewModel
        {
            get;
        }
        #endregion

        #region Methods
        protected void UpdateParameterInCollection(
            NameValueCollection collection, string key, string parameter)
        {
            if (String.IsNullOrEmpty(parameter))
            {
                if (collection[key] != null)
                    collection.Remove(key);
                return;
            }

            collection[key] = parameter;
        }

        protected NameValueCollection CreateQueryCollection(string baseQuery, ListQueryParameters parameters)
        {
            NameValueCollection retVal = HttpUtility.ParseQueryString(baseQuery);
            UpdateParametersInNameValueCollection(retVal, parameters);
            return retVal;
        }

        protected virtual void UpdateParametersInNameValueCollection(NameValueCollection retVal, ListQueryParameters listParameters)
        {
            UpdateParameterInCollection(retVal, "PageBegin", listParameters.PageBegin.ToString());
            UpdateParameterInCollection(retVal, "PageEnd", listParameters.PageEnd.ToString());
        }

        #endregion Methods
    }
}
